/**
 * @file Font.cpp
 *
 * @date 13/02/2012
 * @author Tales 
 *
 */

#include "Font.hpp"

namespace wolf {
int Font::fontLength() const {
	return charWidth('m');
}
Font::~Font() {
}
int Font::charHeight(Uint16 c) const {
	return fontSize();
}

void Font::writeText(const string & str, SDL_Surface *dst, int x, int y,
		const Color & color) {
	writeText(str.c_str(), dst, x, y, color);
}

void Font::writeText(const char *str, SDL_Surface *dst, int x, int y,
		const Color & color) {
	int dx = 0;
	int dy = 0;
	for (const char *i = str; *i != 0; ++i) {
		if (*i != '\n') {
			char currentByte = *i;
			Uint16 character = 0;
			if (currentByte & 0x80) {
				if ((currentByte & 0xf0) == 0xf0) { // todo: support characters larger than 16bits and check for bad format.
					continue;
				} else if ((currentByte & 0xe0) == 0x0f) {
					character = (currentByte & 0x0f) << 12;
					character |= (i[1] & 0x3f) << 6;
					character |= (i[2] & 0x3f);
					i += 2;
				} else if ((currentByte & 0xc0) == 0xc0) {
					character = (currentByte & 0x1f) << 6;
					character |= (i[1] & 0x3f);
					++i;
				} else
					continue;
				writeChar(character, dst, x + dx, y + dy, color);
				dx += charWidth(character);
			} else {
				writeChar(*i, dst, x + dx, y + dy, color);
				dx += charWidth(*i);
			}
		} else {
			dx = 0;
			dy += fontSize();
		}
	}

}

void Font::textSize(const string & str, int & w, int & h) {
	textSize(str.c_str(), w, h);

}

void Font::textSize(const char *str, int & w, int & h) {
	int dx = 0;
	int lines = 1;
	w = 0;
	h = 0;
	for (const char *i = str; *i != 0; ++i) {
		if (*i != '\n') {
			dx += charWidth(*i);
		} else {
			w = max(w, dx);
			dx = 0;
			++lines;
		}
	}

	h = lines * fontSize();
	w = max(w, dx);
}

} // namespace wolf

